const prisma = require('../utils/prisma');
const { success, error } = require('../utils/response');

/**
 * 获取菜单列表
 * @route GET /api/menus
 */
const getMenus = async (req, res) => {
  try {
    const menus = await prisma.menu.findMany({
      include: {
        items: {
          include: {
            dish: true
          }
        }
      },
      orderBy: {
        date: 'desc'
      }
    });
    
    return success(res, menus);
  } catch (err) {
    console.error('Get menus error:', err);
    return error(res, 'Failed to get menus', 500);
  }
};

/**
 * 获取今日菜单
 * @route GET /api/menus/today
 */
const getTodayMenu = async (req, res) => {
  try {
    // 获取今天的日期（不包含时间）
    const today = new Date();
    today.setHours(0, 0, 0, 0);
    
    const tomorrow = new Date(today);
    tomorrow.setDate(tomorrow.getDate() + 1);
    
    // 查找今日菜单
    const todayMenu = await prisma.menu.findFirst({
      where: {
        date: {
          gte: today,
          lt: tomorrow
        },
        isToday: true
      },
      include: {
        items: {
          include: {
            dish: true
          }
        }
      }
    });
    
    if (!todayMenu) {
      return success(res, null, 'No menu for today');
    }
    
    // 格式化菜单数据
    const formattedMenu = {
      id: todayMenu.id,
      date: todayMenu.date,
      remark: todayMenu.remark,
      dishes: todayMenu.items.map(item => ({
        id: item.dish.id,
        name: item.dish.name,
        description: item.dish.description,
        image: item.dish.image,
        count: item.count
      }))
    };
    
    return success(res, formattedMenu);
  } catch (err) {
    console.error('Get today menu error:', err);
    return error(res, 'Failed to get today menu', 500);
  }
};

/**
 * 获取历史菜单
 * @route GET /api/menus/history
 */
const getHistoryMenus = async (req, res) => {
  try {
    const historyMenus = await prisma.menu.findMany({
      where: {
        isToday: false
      },
      include: {
        items: {
          include: {
            dish: true
          }
        }
      },
      orderBy: {
        date: 'desc'
      },
      take: 10
    });
    
    // 格式化菜单数据
    const formattedMenus = historyMenus.map(menu => ({
      id: menu.id,
      date: menu.date,
      remark: menu.remark,
      dishes: menu.items.map(item => ({
        id: item.dish.id,
        name: item.dish.name,
        description: item.dish.description,
        image: item.dish.image,
        count: item.count
      }))
    }));
    
    return success(res, formattedMenus);
  } catch (err) {
    console.error('Get history menus error:', err);
    return error(res, 'Failed to get history menus', 500);
  }
};

/**
 * 获取指定菜单
 * @route GET /api/menus/:id
 */
const getMenuById = async (req, res) => {
  try {
    const { id } = req.params;
    
    const menu = await prisma.menu.findUnique({
      where: { id },
      include: {
        items: {
          include: {
            dish: true
          }
        }
      }
    });
    
    if (!menu) {
      return error(res, 'Menu not found', 404);
    }
    
    // 格式化菜单数据
    const formattedMenu = {
      id: menu.id,
      date: menu.date,
      remark: menu.remark,
      dishes: menu.items.map(item => ({
        id: item.dish.id,
        name: item.dish.name,
        description: item.dish.description,
        image: item.dish.image,
        count: item.count
      }))
    };
    
    return success(res, formattedMenu);
  } catch (err) {
    console.error('Get menu error:', err);
    return error(res, 'Failed to get menu', 500);
  }
};

/**
 * 创建菜单
 * @route POST /api/menus
 */
const createMenu = async (req, res) => {
  try {
    const { date, dishes, remark, isToday } = req.body;
    
    if (!date || !dishes || !Array.isArray(dishes) || dishes.length === 0) {
      return error(res, 'Date and dishes are required', 400);
    }
    
    // 创建菜单
    const menu = await prisma.menu.create({
      data: {
        date: new Date(date),
        remark,
        isToday: isToday || false
      }
    });
    
    // 创建菜单项
    const menuItems = [];
    
    for (const dish of dishes) {
      // 检查菜品是否存在
      const existingDish = await prisma.dish.findUnique({
        where: { id: dish.id }
      });
      
      if (!existingDish) {
        continue; // 跳过不存在的菜品
      }
      
      const menuItem = await prisma.menuItem.create({
        data: {
          menuId: menu.id,
          dishId: dish.id,
          count: dish.count || 1
        }
      });
      
      menuItems.push(menuItem);
    }
    
    // 如果是今日菜单，将其他菜单的 isToday 设为 false
    if (isToday) {
      await prisma.menu.updateMany({
        where: {
          id: { not: menu.id },
          isToday: true
        },
        data: {
          isToday: false
        }
      });
    }
    
    return success(res, {
      id: menu.id,
      date: menu.date,
      remark: menu.remark,
      isToday: menu.isToday,
      items: menuItems
    }, 'Menu created successfully', 201);
  } catch (err) {
    console.error('Create menu error:', err);
    return error(res, 'Failed to create menu', 500);
  }
};

/**
 * 更新菜单
 * @route PUT /api/menus/:id
 */
const updateMenu = async (req, res) => {
  try {
    const { id } = req.params;
    const { date, dishes, remark, isToday } = req.body;
    
    // 检查菜单是否存在
    const existingMenu = await prisma.menu.findUnique({
      where: { id }
    });
    
    if (!existingMenu) {
      return error(res, 'Menu not found', 404);
    }
    
    // 更新菜单
    const updateData = {};
    
    if (date) updateData.date = new Date(date);
    if (remark !== undefined) updateData.remark = remark;
    if (isToday !== undefined) updateData.isToday = isToday;
    
    const updatedMenu = await prisma.menu.update({
      where: { id },
      data: updateData
    });
    
    // 如果提供了菜品，更新菜单项
    if (dishes && Array.isArray(dishes)) {
      // 删除现有菜单项
      await prisma.menuItem.deleteMany({
        where: { menuId: id }
      });
      
      // 创建新菜单项
      for (const dish of dishes) {
        // 检查菜品是否存在
        const existingDish = await prisma.dish.findUnique({
          where: { id: dish.id }
        });
        
        if (!existingDish) {
          continue; // 跳过不存在的菜品
        }
        
        await prisma.menuItem.create({
          data: {
            menuId: id,
            dishId: dish.id,
            count: dish.count || 1
          }
        });
      }
    }
    
    // 如果是今日菜单，将其他菜单的 isToday 设为 false
    if (isToday) {
      await prisma.menu.updateMany({
        where: {
          id: { not: id },
          isToday: true
        },
        data: {
          isToday: false
        }
      });
    }
    
    return success(res, updatedMenu, 'Menu updated successfully');
  } catch (err) {
    console.error('Update menu error:', err);
    return error(res, 'Failed to update menu', 500);
  }
};

/**
 * 删除菜单
 * @route DELETE /api/menus/:id
 */
const deleteMenu = async (req, res) => {
  try {
    const { id } = req.params;
    
    // 检查菜单是否存在
    const existingMenu = await prisma.menu.findUnique({
      where: { id }
    });
    
    if (!existingMenu) {
      return error(res, 'Menu not found', 404);
    }
    
    // 删除菜单项
    await prisma.menuItem.deleteMany({
      where: { menuId: id }
    });
    
    // 删除菜单
    await prisma.menu.delete({
      where: { id }
    });
    
    return success(res, null, 'Menu deleted successfully');
  } catch (err) {
    console.error('Delete menu error:', err);
    return error(res, 'Failed to delete menu', 500);
  }
};

module.exports = {
  getMenus,
  getTodayMenu,
  getHistoryMenus,
  getMenuById,
  createMenu,
  updateMenu,
  deleteMenu
};
